package org.levi.demo.org.levi.demo.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.levi.demo.org.levi.demo.service.AutoDeliverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class AutoDeliveryServiceImpl implements AutoDeliverService {

    public static final long RESUME_OPEN_STATUS_FLAG = 3;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean autoDeliverResume(long userId) {

        String requestUrl = "http://resume-service/resume/openState/" + userId;
        Long state = restTemplate.getForEntity(requestUrl, Long.class).getBody();
        System.out.println("从简历服务获取状态成功！");
        if (state == RESUME_OPEN_STATUS_FLAG) {
            return true;
        }
        return false;
    }

    @Override
    @HystrixCommand(
            threadPoolKey = "resume-search-pool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "2"),
                    @HystrixProperty(name = "maxQueueSize", value = "20"),
            },
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000"),
                    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "1000"),
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "3"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "3000"),
            },
            fallbackMethod = "autoDeliverResumeFallback"
    )
    public boolean autoDeliverResumeTimeout(long userId, long timeout) {

        //int a = 1/0;

        try {
            TimeUnit.MILLISECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }

    public boolean autoDeliverResumeFallback(long userId,long timeout){
        //TimeUnit.MILLISECONDS.sleep(timeout);
        System.out.println("进入到熔断里面了。");
        return false;
    }
}
